package com.yc.io.img;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.ImageIcon;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class HandleImg {
	
	/*
     * 图片缩放,w，h为缩放的目标宽度和高度
     * src为源文件目录，dest为缩放后保存目录
     */
    public static void zoomImage(String src,String dest,int w,int h) throws Exception {
        
        double wr=0,hr=0;
        File srcFile = new File(src);
        File destFile = new File(dest);

        BufferedImage bufImg = ImageIO.read(srcFile); //读取图片
        Image Itemp = bufImg.getScaledInstance(w, h, bufImg.SCALE_SMOOTH);//设置缩放目标图片模板
        
        wr=w*1.0 / bufImg.getWidth();     //获取缩放比例
        hr=h*1.0 / bufImg.getHeight();

        AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(wr, hr), null);
        Itemp = ato.filter(bufImg, null);
        try {
            ImageIO.write((BufferedImage) Itemp,dest.substring(dest.lastIndexOf(".")+1), destFile); //写入缩减后的图片
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    

	/**
	 * 截取图片
	 * 
	 * @param src
	 * @param dest
	 * @param w
	 * @param h
	 * @param format
	 * @throws Exception
	 */
	public static void readUsingImageReader(String src, String dest, int w1, int h1, int w2, int h2, String format) throws Exception {
		// 取得图片读入器
		Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(format);
		ImageReader reader = (ImageReader) readers.next();
		// 取得图片读入流
		InputStream source = new FileInputStream(src);
//		getHead(source);
		ImageInputStream iis = ImageIO.createImageInputStream(source);
		reader.setInput(iis, true);
		// 图片参数
		ImageReadParam param = reader.getDefaultReadParam();
		// 默认截取从0,0 开始，可以自己定义设置
		Rectangle rect = new Rectangle(w1, h1, w2, h2);
		param.setSourceRegion(rect);
		BufferedImage bi = reader.read(0, param);
//		bi.getType()
		
		ImageIO.write(bi, format, new File(dest));

	}
	
	public static void getHead(InputStream in) {
		byte[] b = new byte[8];
		try {
			in.read(b);
			System.err.println(toHexString1(b));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
    /**
     * 数组转成十六进制字符串
     * @param byte[]
     * @return HexString
     */
    public static String toHexString1(byte[] b){
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < b.length; ++i){
            buffer.append(toHexString1(b[i]));
        }
        return buffer.toString();
    }
    public static String toHexString1(byte b){
        String s = Integer.toHexString(b & 0xFF);
        if (s.length() == 1){
            return "0" + s;
        }else{
            return s;
        }
    }
    
    /**
     * 根据要求截取图片
     * @param src
     * @param dest
     * @param w
     * @param h
     */
    public static void aotoSubImg(String src,String dest,int w,int h) {
    	try {
    		String filetype = src.substring(src.lastIndexOf(".") + 1);
    		
    		//获取原图宽高和格式
        	BufferedImage bufImg = ImageIO.read(new File(src)); //读取图片
        	int width_src = bufImg.getWidth();
        	int height_src = bufImg.getHeight();
        	int imgtype = bufImg.getType();
        	System.out.println("width_src =" + width_src + ",height_src =" + height_src + ",w =" + w + ", h=" + h);
        	//获取需要截取的长宽
        	Number[] ned = getLengthAndWidth3(width_src, height_src, w, h);
        	int sublong;
        	BufferedImage bi;
        	if (ned[0].intValue() == width_src) {//以宽为基准
        		sublong = (height_src - ned[1].intValue())/2;
        		bi = readUsingImageReader2(src, dest, 0, sublong, ned[0].intValue(), ned[1].intValue(), filetype);
        	} else {
        		sublong = (width_src - ned[0].intValue())/2;
        		bi = readUsingImageReader2(src, dest, sublong, 0, ned[0].intValue(), ned[1].intValue(), filetype);
        	}
        	//截图
        	
        	if (ned[2].intValue() == 1) {
        		//缩小图片
        		zoomImage2(bi, dest, ned[3].doubleValue());
        		
        	} else {
        		//直接输出
        		zoomImage2(bi, dest, 1.0);
        	}
        	
        	//输出图片
    		System.out.println("-----------------------------------------");
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	
    }
    
    public static void zoomImage1(String src, String dest, Double rate) throws Exception {
      File srcFile = new File(src);
      File destFile = new File(dest);
//      
//      long fileSize = srcFile.length();
//      if(fileSize < size * 1024)   //文件大于size k时，才进行缩放,注意：size以K为单位
//          return;
//      
//      Double rate = (size * 1024 * 0.5) / fileSize; // 获取长宽缩放比例
//      
      BufferedImage bufImg = ImageIO.read(srcFile);
      
//      Image Itemp = bufImg.getScaledInstance(bufImg.getWidth(), bufImg.getHeight(), bufImg.SCALE_SMOOTH);
      Image Itemp = bufImg.getScaledInstance(bufImg.getWidth(), bufImg.getHeight(), Image.SCALE_SMOOTH);
          
      AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(rate, rate), null);
      Itemp = ato.filter(bufImg, null);
      try {
          ImageIO.write((BufferedImage) Itemp,dest.substring(dest.lastIndexOf(".")+1), destFile);
      } catch (Exception ex) {
          ex.printStackTrace();
      }
  }
    
    public static void zoomImage2(BufferedImage bufImg,String dest,Double rate) throws Exception {
//        File srcFile = new File(src);
        File destFile = new File(dest);
//        
//        long fileSize = srcFile.length();
//        if(fileSize < size * 1024)   //文件大于size k时，才进行缩放,注意：size以K为单位
//            return;
//        
//        Double rate = (size * 1024 * 0.5) / fileSize; // 获取长宽缩放比例
//        
//        BufferedImage bufImg = ImageIO.read(srcFile);
        
//        Image Itemp = bufImg.getScaledInstance(bufImg.getWidth(), bufImg.getHeight(), bufImg.SCALE_SMOOTH);
        Image Itemp = bufImg.getScaledInstance(bufImg.getWidth(), bufImg.getHeight(), Image.SCALE_SMOOTH);
            
        AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(rate, rate), null);
        Itemp = ato.filter(bufImg, null);
        try {
            ImageIO.write((BufferedImage) Itemp,dest.substring(dest.lastIndexOf(".")+1), destFile);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public static void readUsingImageReader1(String src, String dest, int w1, int h1, int w2, int h2, String format) throws Exception {
		// 取得图片读入器
		Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(format);
		ImageReader reader = (ImageReader) readers.next();
		// 取得图片读入流
		InputStream source = new FileInputStream(src);
		ImageInputStream iis = ImageIO.createImageInputStream(source);
		reader.setInput(iis, true);
		// 图片参数
		ImageReadParam param = reader.getDefaultReadParam();
		// 默认截取从0,0 开始，可以自己定义设置
		Rectangle rect = new Rectangle(w1, h1, w2, h2);
		param.setSourceRegion(rect);
		BufferedImage bi = reader.read(0, param);//Not a JPEG file: starts with 0x47 0x49
		
		ImageIO.write(bi, format, new File(dest));

	}
    
    
    /**
     *  宽从
     * @param src
     * @param dest
     * @param w
     * @param h
     * @param format
     * @throws Exception
     */
    public static BufferedImage readUsingImageReader2(String src, String dest, int w1, int h1, int w2, int h2, String format) throws Exception {
		// 取得图片读入器
		Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(format);
		ImageReader reader = (ImageReader) readers.next();
		// 取得图片读入流
		InputStream source = new FileInputStream(src);
		ImageInputStream iis = ImageIO.createImageInputStream(source);
		reader.setInput(iis, true);
		// 图片参数
		ImageReadParam param = reader.getDefaultReadParam();
		// 默认截取从0,0 开始，可以自己定义设置
		Rectangle rect = new Rectangle(w1, h1, w2, h2);
		param.setSourceRegion(rect);
		return reader.read(0, param);//Not a JPEG file: starts with 0x47 0x49
		
//		ImageIO.write(bi, format, new File(dest));

	}
    
    /*
     * 图片按比率缩放
     * size为文件大小
     */
    public static void zoomImage(String src,String dest,Integer size) throws Exception {
        File srcFile = new File(src);
        File destFile = new File(dest);
        
        long fileSize = srcFile.length();
        if(fileSize < size * 1024)   //文件大于size k时，才进行缩放,注意：size以K为单位
            return;
        
        Double rate = (size * 1024 * 0.5) / fileSize; // 获取长宽缩放比例
        
        BufferedImage bufImg = ImageIO.read(srcFile);
        Image Itemp = bufImg.getScaledInstance(bufImg.getWidth(), bufImg.getHeight(), bufImg.SCALE_SMOOTH);
            
        AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(rate, rate), null);
        Itemp = ato.filter(bufImg, null);
        try {
            ImageIO.write((BufferedImage) Itemp,dest.substring(dest.lastIndexOf(".")+1), destFile);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    /**
     * 注意：长度可以用浮点数一般计算（长度就是像素数，本身就不需要小数点），但比例要精确计算
     * @param priWidth
     * @param priHeight
     * @param needWidth
     * @param needHeight
     * @return
     */
    public static Number[] getLengthAndWidth2(double priWidth, double priHeight, double needWidth, double needHeight) {
    	System.out.println("priWidth=" + priWidth + ", priHeight=" + priHeight + " needWidth=" + needWidth + ", needHeight=" + needHeight);
    	Number[] result = new Number[4];//[Length, Width, flag, ratio]   长，宽，是否缩小至实际大小比例（0：否，  1  是）,比例
    	
    	double finWidth, finHeight;
    	
    	double widthRatio;
    	double heightRatio;
    	
    	
    	if (needWidth >= priWidth || needHeight >= priHeight) {//需要缩小的
    		widthRatio = (needWidth - priWidth)/priWidth;
    		heightRatio = (needHeight - priHeight)/priHeight;
        	if (widthRatio > heightRatio) {
        		finWidth = priWidth;
        		finHeight = needHeight*(priWidth/needWidth);
        	} else {
        		finHeight = priHeight;
        		finWidth = needWidth*(priHeight/needHeight);
        	}
        	
        	result[2] = 0;
    		result[3] = 0.0;
    		
    	} else {//需要放大，最后要缩小
    		widthRatio = (priWidth - needWidth)/needWidth;
    		heightRatio = (priHeight - needHeight)/needHeight;
    		
    		if (widthRatio > heightRatio) {
    			finHeight = priHeight;
    			finWidth = needWidth*(priHeight/needHeight);
    			result[3] = needHeight/priHeight;
    		} else {
    			finWidth = priWidth;
    			finHeight = needHeight*(priWidth/needWidth);
    			result[3] = needWidth/priWidth;
    		}
    		result[2] = 1;
    		
    	}
    	result[0] = (int) finWidth;
    	result[1] = (int) finHeight;
    	System.out.println("finWidth=" + finWidth + ", finHeight=" + finHeight);
    	
    	
    	return result;
    }
    
    
    

    public static Number[] getLengthAndWidth3(double priWidth, double priHeight, double needWidth, double needHeight) {
    	System.out.println("----------------------------------------------");
    	System.out.println("priWidth=" + priWidth + ", priHeight=" + priHeight + " needWidth=" + needWidth + ", needHeight=" + needHeight);
    	Number[] result = new Number[4];//[Length, Width, flag, ratio]   长，宽，是否缩小至实际大小比例（0：否，  1  是）,比例
    	
    	double finWidth, finHeight;
    	
    	double widthRatio;
    	double heightRatio;
    	
    	widthRatio = (needWidth - priWidth)/((needWidth > priWidth)?needWidth:priWidth);
		heightRatio = (needHeight - priHeight)/((needHeight > priHeight)?needHeight:priHeight);
		if (widthRatio > heightRatio) {
    		finWidth = priWidth;
    		finHeight = needHeight*(priWidth/needWidth);
    		result[3] = (widthRatio > 0)?(priWidth/needWidth):(needWidth/priWidth);
    	} else {
    		finHeight = priHeight;
    		finWidth = needWidth*(priHeight/needHeight);
    		result[3] = (heightRatio > 0)?(priHeight/needHeight):(needHeight/priHeight);
    	}
		result[2] = (needWidth >= priWidth || needHeight >= priHeight)?0:1;
		
    	result[0] = (int) finWidth;
    	result[1] = (int) finHeight;
    	System.out.println("finWidth=" + finWidth + ", finHeight=" + finHeight + " ,ifchangetoSmall=" + result[2] + ", redio=" + result[3]);
    	
    	return result;
    }
    
    
    
    /**
     * 缩放，截取出一个像要的大小的图片（可能要的是10x10，但返回5x5[如果原图只有5x5]），参考的是原图（即上限是原图），而目标是个显示截取窗口
     * 最终的长宽都不得超过原来的长宽，也就是说是：在原图基础上截取一个 目标比例的最大图
     * 也就是说，我们绝不放大，只能缩小和截取
     * @param priLength
     * @param priWidth
     * @param needLength
     * @param needWidth
     * @return 【最终长，最终宽，是否需要缩放，缩放比例】
     */
    public static Number[] getLengthAndWidth(double priLength, double priWidth, double needLength, double needWidth) {
    	System.out.println("priLength=" + priLength + ", priWidth=" + priWidth + " needLength=" + needLength + ", needWidth=" + needWidth);
    	Number[] result = new Number[4];//[Length, Width, flag, ratio]   长，宽，是否缩小至实际大小比例（0：否，  1  是）,比例
    	
    	double finLength, finWidth;
    	
    	double addLengthRatio = (needLength - priLength)/priLength;
    	double addWidthRatio = (needWidth - priWidth)/priWidth;
    	
    	//有至少一边比原始长度长: 把需求比原始更为大的一边缩小至 原始长度，另一边同比例缩小（另一边不论比原来大还是小缩小后都足够），然后截取
    	if (addLengthRatio >= 0 || addWidthRatio >= 0) {
    		
    		if (addLengthRatio - addWidthRatio > 0) {
    			finLength = priLength;
    			finWidth = needWidth*(1-addLengthRatio);//缩小同样的比例
    			
    			//截取高度
    		} else {
    			finWidth = priWidth;
    			finLength = needLength*(1-addWidthRatio);
    			
    			//截取长度
    		}
    		
    		result[2] = 0;
    		result[3] = 0.0;
    		
    	} else {//需求的比原始都短：按需求比例更接近小的一边扩大至原始长度，另一边同比例扩大(另一边一定不会超过原始长度)，然后截取，最后缩小
    		if (addLengthRatio > addWidthRatio) {
    			finLength = priLength;
    			finWidth = needWidth*(1 - addLengthRatio);
    			
    			//截取高度
    			
    		} else {
    			finWidth = priWidth;
    			finLength = needLength*(1 - addWidthRatio);
    			
    			
    			//截取长度
    		}
    		result[2] = 1;
    		result[3] = -addWidthRatio;
    	}
    	
    	result[0] = (int) finLength;
    	result[1] = (int) finWidth;
    	
    	System.out.println("finLength=" + finLength + ", finWidth=" + finWidth);
    	
    	return result;
    }
    
    /**
     * 缩放，截取出一个像要的大小的图片，和上面不同的是，这里相要的结果是多大就必须是多大（不可是同比例的缩小版）
     * 即
     * @param priWeight
     * @param priHeight
     * @param needWeight
     * @param needHeight
     * @return
     */
    public static Number[] subLenght(double priWeight, double priHeight, double needWeight, double needHeight) {
    	double resultRatio = 0.0;
    	int tagSub = 0;//截取目标  1 宽   2高
    	double tagLen = 0.0;//截取的目标最终长度
    	
    	
    	double weightChangeRatio = (needWeight - priWeight)/priWeight;
    	double heightChangeRatio = (needHeight - priHeight)/priHeight;
    	//原图的宽高都比目标图大[weightChangeRatio,heightChangeRatio都小于0，以绝对值小的那个缩小]
    	if (weightChangeRatio < 0 && heightChangeRatio < 0) {
    		if (Math.abs(weightChangeRatio) < Math.abs(heightChangeRatio)) {//宽度更接近,缩小宽度，截取高度
        		resultRatio = needWeight/priWeight;
        		tagSub = 2;
        		tagLen = needHeight;
        	} else {//高度更接近，缩小高度，截取宽度
        		resultRatio = needHeight/priHeight;
        		tagSub = 1;
        		tagLen = needWeight;
        	}
    	} else if (weightChangeRatio < 0 || heightChangeRatio < 0) {
    		//原图的宽或高比目标图大
    		if (weightChangeRatio < 0) {//高度比原图大，宽度比原图小：放大高度，截取宽度
    			resultRatio = needHeight/priHeight;
    			tagSub = 1;
    			tagLen = needWeight;
    		} else {//宽度比原图大，高度比原图小：放大宽度，截取高度
    			resultRatio = needWeight/priWeight;
        		tagSub = 2;
        		tagLen = needHeight;
    		}
    		
    	} else {
    		//原图的宽高都比目标图小
    		if (weightChangeRatio < heightChangeRatio) {//高度相差更远，放大高度，截取宽度
    			resultRatio = needHeight/priHeight;
    			tagSub = 1;
    			tagLen = needWeight;
    		} else {//宽度相差更远，放大宽度，截取高度
    			resultRatio = needWeight/priWeight;
        		tagSub = 2;
        		tagLen = needHeight;
    		}
    		
    	}
    	System.out.println("结果： resultRatio=" + resultRatio + ", tagSub=" + tagSub + ", tagLen=" + tagLen);
    	
    	return new Number[] {resultRatio, tagSub, tagLen};
    }
    
    /**
     * 根据后面的计算要求，优化subLenght
     * @param priWeight
     * @param priHeight
     * @param needWeight
     * @param needHeight
     * @return
     */
    public static Number[] subLenght2(double priWeight, double priHeight, double needWeight, double needHeight) {
    	Number[] result = new Number[2];
    	
    	double weightChangeRatio = (needWeight - priWeight)/priWeight;
    	double heightChangeRatio = (needHeight - priHeight)/priHeight;
    	
    	if (weightChangeRatio < heightChangeRatio) {//高度相差更远，放大高度，截取宽度
    		result[0] = needHeight/priHeight;
    		result[1] = 1;
		} else {//宽度相差更远，放大宽度，截取高度
			result[0] = needWeight/priWeight;
			result[1] = 2;
		}
    	System.out.println("result:[" + result[0] + ", " + result[1] + "]");
    	return result;
    }
    
    /** 
     * 纵向拼接图片（两张） 
     * @param firstSrcImagePath 读取的第一张图片 
     * @param secondSrcImagePath    读取的第二张图片 
     * @param imageFormat 图片写入格式 
     * @param toPath    图片写入路径 
     */  
    public static void joinImagesVertical(String firstSrcImagePath, String secondSrcImagePath,String imageFormat, String toPath){    
        try {    
            //读取第一张图片      
            File  fileOne  =  new  File(firstSrcImagePath);      
            BufferedImage  imageOne = ImageIO.read(fileOne);      
            int  width  =  imageOne.getWidth();//图片宽度      
            int  height  =  imageOne.getHeight();//图片高度      
            //从图片中读取RGB      
            int[]  imageArrayOne  =  new  int[width*height];      
            imageArrayOne  =  imageOne.getRGB(0,0,width,height,imageArrayOne,0,width);      
         
            //对第二张图片做相同的处理      
            File  fileTwo  =  new  File(secondSrcImagePath);      
            BufferedImage  imageTwo  =  ImageIO.read(fileTwo);   
            int width2 = imageTwo.getWidth();  
            int height2 = imageTwo.getHeight();  
            int[]   ImageArrayTwo  =  new  int[width2*height2];      
            ImageArrayTwo  =  imageTwo.getRGB(0,0,width,height,ImageArrayTwo,0,width);      
            //ImageArrayTwo  =  imageTwo.getRGB(0,0,width2,height2,ImageArrayTwo,0,width2);   
         
            //生成新图片  
            //int width3 = (width>width2 || width==width2)?width:width2;  
            BufferedImage  imageNew  =  new  BufferedImage(width,height*2,BufferedImage.TYPE_INT_RGB);      
            //BufferedImage  imageNew  =  new  BufferedImage(width3,height+height2,BufferedImage.TYPE_INT_RGB);      
            imageNew.setRGB(0,0,width,height,imageArrayOne,0,width);//设置上半部分的RGB      
            imageNew.setRGB(0,height,width,height,ImageArrayTwo,0,width);//设置下半部分的RGB  
            //imageNew.setRGB(0,height,width2,height2,ImageArrayTwo,0,width2);//设置下半部分的RGB      
         
            File  outFile  =  new  File(toPath);      
            ImageIO.write(imageNew,  imageFormat,  outFile);//写图片  
        } catch (Exception e) {    
            e.printStackTrace();    
        }    
    }
    
    public static void joinImagesVertical(String firstSrcImagePath, String secondSrcImagePath, String threeSrcImagePath,String imageFormat, String toPath){    
        try {    
            //读取第一张图片      
            File  fileOne  =  new  File(firstSrcImagePath);      
            BufferedImage  imageOne = ImageIO.read(fileOne);      
            int  width  =  imageOne.getWidth();//图片宽度      
            int  height  =  imageOne.getHeight();//图片高度      
            //从图片中读取RGB      
            int[]  imageArrayOne  =  new  int[width*height];      
            imageArrayOne  =  imageOne.getRGB(0,0,width,height,imageArrayOne,0,width);      
         
            //对第二张图片做相同的处理      
            File  fileTwo  =  new  File(secondSrcImagePath);      
            BufferedImage  imageTwo  =  ImageIO.read(fileTwo);   
            int width2 = imageTwo.getWidth();  
            int height2 = imageTwo.getHeight();  
            int[]   ImageArrayTwo  =  new  int[width2*height2];      
            ImageArrayTwo  =  imageTwo.getRGB(0,0,width,height,ImageArrayTwo,0,width);      
            //ImageArrayTwo  =  imageTwo.getRGB(0,0,width2,height2,ImageArrayTwo,0,width2);
            
            //对第三张图片做相同的处理      
            File  fileThree  =  new  File(threeSrcImagePath);      
            BufferedImage  imageThree  =  ImageIO.read(fileThree);   
            int width3 = imageThree.getWidth();  
            int height3 = imageThree.getHeight();  
            int[]   ImageArrayThree  =  new  int[width3*height3];      
            ImageArrayThree  =  imageThree.getRGB(0,0,width3,height3,ImageArrayThree,0,width3);
         
            //生成新图片  
            //int width3 = (width>width2 || width==width2)?width:width2;  
            BufferedImage  imageNew  =  new  BufferedImage(width*2,height*2,BufferedImage.TYPE_INT_RGB);      
            //BufferedImage  imageNew  =  new  BufferedImage(width3,height+height2,BufferedImage.TYPE_INT_RGB);      
            imageNew.setRGB(0,0,width,height,imageArrayOne,0,width);//设置上半部分的左半边RGB
            imageNew.setRGB(width,0,width,height,ImageArrayTwo,0,width);//设置上半部分的右半边RGB
            
            imageNew.setRGB(0,height,width3,height3,ImageArrayThree,0,width3);//设置下半部分的RGB  
            //imageNew.setRGB(0,height,width2,height2,ImageArrayTwo,0,width2);//设置下半部分的RGB      
         
            File  outFile  =  new  File(toPath);      
            ImageIO.write(imageNew,  imageFormat,  outFile);//写图片  
        } catch (Exception e) {    
            e.printStackTrace();    
        }    
    }
    
    /** 
     * 纵向拼接图片（两张） 【优化：两个图之间增加一像素的白色分割线】
     * @param firstSrcImagePath 读取的第一张图片 
     * @param secondSrcImagePath    读取的第二张图片 
     * @param imageFormat 图片写入格式 
     * @param toPath    图片写入路径 
     */  
    public static void joinImagesVertical2(String firstSrcImagePath, String secondSrcImagePath,String imageFormat, String toPath){    
        try {    
            //读取第一张图片      
            File  fileOne  =  new  File(firstSrcImagePath);      
            BufferedImage  imageOne = ImageIO.read(fileOne);      
            int  width  =  imageOne.getWidth();//图片宽度      
            int  height  =  imageOne.getHeight();//图片高度      
            //从图片中读取RGB      
            int[]  imageArrayOne  =  new  int[width*height];      
            imageArrayOne  =  imageOne.getRGB(0,0,width,height,imageArrayOne,0,width);      
         
            //对第二张图片做相同的处理      
            File  fileTwo  =  new  File(secondSrcImagePath);      
            BufferedImage  imageTwo  =  ImageIO.read(fileTwo);   
            int width2 = imageTwo.getWidth();  
            int height2 = imageTwo.getHeight();  
            int[]   ImageArrayTwo  =  new  int[width2*height2];      
            ImageArrayTwo  =  imageTwo.getRGB(0,0,width,height,ImageArrayTwo,0,width);      
            //ImageArrayTwo  =  imageTwo.getRGB(0,0,width2,height2,ImageArrayTwo,0,width2); 
            
            int[] lineArray = new int[width];
            for (int i = 0; i < lineArray.length; i++) {
            	lineArray[i] = 0;
			}
         
            //生成新图片  
            //int width3 = (width>width2 || width==width2)?width:width2;  
            BufferedImage  imageNew  =  new  BufferedImage(width,height*2,BufferedImage.TYPE_INT_RGB);      
            //BufferedImage  imageNew  =  new  BufferedImage(width3,height+height2,BufferedImage.TYPE_INT_RGB);      
            imageNew.setRGB(0,0,width,height,imageArrayOne,0,width);//设置上半部分的RGB
            
//            imageNew.setRGB(0,height,width,1,lineArray,0,width);//设置上半部分的RGB
            
            imageNew.setRGB(0,height+1, width, height-1, ImageArrayTwo,0,width);//设置下半部分的RGB  
            //imageNew.setRGB(0,height,width2,height2,ImageArrayTwo,0,width2);//设置下半部分的RGB      
         
            File  outFile  =  new  File(toPath);      
            ImageIO.write(imageNew,  imageFormat,  outFile);//写图片  
        } catch (Exception e) {    
            e.printStackTrace();    
        }    
    }
    
    
    /**
     * 定长度截取图片
     * @throws Exception 
     */
    public static void subImg(String srcImgPath, String destImgPath, int needWeight, int needHeight) throws Exception {
//    	String srcImgPath = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y1.jpg";// w: 650  h:433
    	// w: 300  h:400 //第一步 缩放图片  高度比较接近，缩放为 w:600  h:400 
//    	String sfImgPath = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y1_sf.jpg";
//    	String destImgPath = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y1_dest.jpg";// w: 300  h:400
    	//获取原图宽高和格式
    	System.out.println("srcImgPath=" + srcImgPath);
    	BufferedImage bufImg = ImageIO.read(new File(srcImgPath)); //读取图片
    	int priWeight = bufImg.getWidth();
    	int priHeight = bufImg.getHeight();
    	String imgType = srcImgPath.substring(srcImgPath.indexOf('.')+1);
    	int imgtype = bufImg.getType();
    	
    	
//    	int needWeight = 300;
//    	int needHeight = 400;
    	
//    	Number[] lens = subLenght(priWeight, priHeight, needWeight, needHeight);
//    	double rate = subLenght2(priWeight, priHeight, needWeight, needHeight);
    	Number[] res = subLenght2(priWeight, priHeight, needWeight, needHeight);
    	//缩放图片
        Image Itemp = bufImg.getScaledInstance(priWeight, priHeight, bufImg.SCALE_SMOOTH);
            
        AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(res[0].doubleValue(), res[0].doubleValue()), null);
        Itemp = ato.filter(bufImg, null);
        try {
            ImageIO.write((BufferedImage) Itemp,destImgPath.substring(destImgPath.lastIndexOf(".")+1), new File(destImgPath));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    	
        //获取缩放完后的宽高
        BufferedImage bufImg_1 = ImageIO.read(new File(destImgPath)); //读取图片
    	int w_1 = bufImg_1.getWidth();
    	int h_1 = bufImg_1.getHeight();
        
    	//截取图片(目前其中一边已经和目标一致，只需要把另一边截即可)
        int ws = 0;
        int hs = 0;
        int w = 0;
        int h = 0;
        if (res[1].intValue() == 1) {//截取宽
        	ws = (w_1 - needWeight)/2;
        	w = needWeight;
        	h = h_1;//第一步缩放完是什么就是什么
        } else {//截取高
        	hs = (h_1 - needHeight)/2;
        	w = w_1;
        	h = needHeight;
        }
        readUsingImageReader1(destImgPath, destImgPath, ws, hs, w, h, imgType);
//        aotoSubImg(destImgPath, destImgPath, needWeight, needHeight);
        
    	
    }
    
    
    

    /**
     * 纵向拼接两张图片
     * @param imgPath1
     * @param imgPath2
     * @param destPath
     * @throws Exception 
     */
    public static void join2Img(String imgPath1, String imgPath2, String destPath) throws Exception {
    	//处理图片1——>临时图片1
    	String img1 = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y1.jpg";
    	String img1_temp = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y1_temp.jpg";
    	subImg(img1, img1_temp, 800, 400);
    	
    	//处理图片2——>临时图片2
    	String img2 = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y2.jpg";
    	String img2_temp = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y2_temp.jpg";
    	subImg(img2, img2_temp, 800, 400);
    	
    	//拼接临时图片1和临时图片2——>最终图片
    	String img1_2 = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y1_y2.jpg";
    	joinImagesVertical(img1_temp, img2_temp, "jpg", img1_2);
    	
    	//删除临时图片1,2
    	
    }
    
    /**
     * 获取单个小图片的大小和位置(左上角的位置)
     * @param destWeight	大图片宽
     * @param destHeight	大图片高
     * @param imgTotal	拼接图片数量，最小2个，最大6个
     * @param index	图片序号【1,2,3,4,5,6】
     * @return【小图片宽，小图片高，小图片左上角位置的x轴大小，小图片左上角位置y轴大小】
     */
    public static int[] getItemImgByDestImg(int destWeight, int destHeight, int imgTotal, int index) {
    	int[] result = new int[4];
    	switch(imgTotal) {
    	case 2:
    		if (index == 1) {
    			result[0] = destWeight;
    			result[1] = destHeight/2;
    			result[2] = 0;
    			result[3] = 0;
    		} else if (index == 2) {
    			result[0] = destWeight;
    			result[1] = destHeight - (destHeight/2);//万一是奇数
    			result[2] = 0;
    			result[3] = destHeight/2;
    		}
    		break;
    	case 3:
    		if (index == 1) {
    			result[0] = destWeight/2;
    			result[1] = destHeight/2;
    			result[2] = 0;
    			result[3] = 0;
    		} else if (index == 2) {
    			result[0] = destWeight - (destWeight/2);
    			result[1] = destHeight/2;
    			result[2] = destWeight/2;
    			result[3] = 0;
    		} else if (index == 3) {
    			result[0] = destWeight;
    			result[1] = destHeight - (destHeight/2);
    			result[2] = 0;
    			result[3] = destHeight/2;
    		}
    		break;
    	case 4:
    		if (index == 1) {
    			result[0] = destWeight/2;
    			result[1] = destHeight/2;
    			result[2] = 0;
    			result[3] = 0;
    		} else if (index == 2) {
    			result[0] = destWeight - (destWeight/2);
    			result[1] = destHeight/2;
    			result[2] = destWeight/2;
    			result[3] = 0;
    		} else if (index == 3) {
    			result[0] = destWeight/2;
    			result[1] = destHeight - (destHeight/2);
    			result[2] = 0;
    			result[3] = destHeight/2;
    		} else if (index == 4) {
    			result[0] = destWeight - destWeight/2;
    			result[1] = destHeight - (destHeight/2);
    			result[2] = destWeight/2;
    			result[3] = destHeight/2;
    		}
    		break;
    	case 5:
    		if (index == 1) {
    			result[0] = destWeight/3;
    			result[1] = destHeight/2;
    			result[2] = 0;
    			result[3] = 0;
    		} else if (index == 2) {
    			result[0] = destWeight/3;
    			result[1] = destHeight/2;
    			result[2] = destWeight/3;
    			result[3] = 0;
    		} else if (index == 3) {
    			result[0] = destWeight - (destWeight / 3 * 2);
    			result[1] = destHeight/2;
    			result[2] = destWeight / 3 * 2;
    			result[3] = 0;
    		} else if (index == 4) {
    			result[0] = destWeight/2;
    			result[1] = destHeight - (destHeight/2);
    			result[2] = 0;
    			result[3] = destHeight/2;
    		} else if (index == 5) {
    			result[0] = destWeight - destWeight/2;
    			result[1] = destHeight - (destHeight/2);
    			result[2] = destWeight/2;
    			result[3] = destHeight/2;
    		}
    		break;
    	case 6:
    		if (index == 1) {
    			result[0] = destWeight/3;
    			result[1] = destHeight/2;
    			result[2] = 0;
    			result[3] = 0;
    		} else if (index == 2) {
    			result[0] = destWeight/3;
    			result[1] = destHeight/2;
    			result[2] = destWeight/3;
    			result[3] = 0;
    		} else if (index == 3) {
    			result[0] = destWeight - (destWeight / 3 * 2);
    			result[1] = destHeight/2;
    			result[2] = destWeight / 3 * 2;
    			result[3] = 0;
    		} else if (index == 4) {
    			result[0] = destWeight/3;
    			result[1] = destHeight - (destHeight/2);
    			result[2] = 0;
    			result[3] = destHeight/2;
    		} else if (index == 5) {
    			result[0] = destWeight/3;
    			result[1] = destHeight - (destHeight/2);
    			result[2] = destWeight/3;
    			result[3] = destHeight/2;
    		} else if (index == 6) {
    			result[0] = destWeight - (destWeight / 3 * 2);
    			result[1] = destHeight - (destHeight/2);
    			result[2] = destWeight / 3 * 2;
    			result[3] = destHeight/2;
    		}
    		break;
    	}
    	System.out.println("getItemImgByDestImg: [" + result[0] + ", " + result[1] + ", " + result[2] + ", " + result[3] + "]");
    	
    	return result;
    }
    
    /**
     * 获取图片长度
     * @param len		大图边长
     * @param total		总小图片数
     * @param margin	边距（只有小图之间有边距，小图和大图之间的外围没有边距）
     * @return			前n-1个图的长度，最后一个图的长度
     */
    public static int[] getItemImgLen(int len, int total, int margin) {
    	//前n-1个的小图长度
    	//如果有小数的话，小数被截掉，所以前n-1个小图按这个长度，总长度只会短不会长
    	int[] itemImgLen = new int[2];
    	itemImgLen[0] = (len - ((total - 1)*margin))/total;
    	itemImgLen[1] = len - itemImgLen[0]*(total-1) - margin*(total-1);
    	
    	return itemImgLen;
    }
    
    public static int getItemLocation(int len, int total, int index, int margin, int avegLen) {
    	return (index - 1) * (avegLen + margin);
    }
    
    /**
     * 获取单个小图片的大小和位置(左上角的位置) 优化：小图和小图之间间隔2像素
     * @param destWeight	大图片宽
     * @param destHeight	大图片高
     * @param imgTotal	拼接图片数量，最小2个，最大6个
     * @param index	图片序号【1,2,3,4,5,6】
     * @return【小图片宽，小图片高，小图片左上角位置的x轴大小，小图片左上角位置y轴大小】
     */
    public static int[] getItemImgByDestImg2(int destWeight, int destHeight, int imgTotal, int index) {
    	int[] result = new int[4];
    	int margin = 2;//边距2
    	
    	
    	
    	int totalW = 0;
    	int totalH = 0;
    	int wIndex = 0;
    	int hIndex = 0;
    	switch(imgTotal) {
    	case 2:
    		if (index == 1) {
    			totalW = 1;
    			wIndex = 1;
    			totalH = 2;
    			hIndex = 1;
    		} else if (index == 2) {
    			totalW = 1;
    			wIndex = 1;
    			totalH = 2;
    			hIndex = 2;
    		}
    		break;
    	case 3:
    		if (index == 1) {
    			totalW = 1;
    			wIndex = 1;
    			totalH = 2;
    			hIndex = 1;
    		} else if (index == 2) {
    			totalW = 2;
    			wIndex = 1;
    			totalH = 2;
    			hIndex = 2;
    		} else if (index == 3) {
    			totalW = 2;
    			wIndex = 2;
    			totalH = 2;
    			hIndex = 2;
    		}
    		break;
    	case 4:
    		if (index == 1) {
    			totalW = 2;
    			wIndex = 1;
    			totalH = 2;
    			hIndex = 1;
    		} else if (index == 2) {
    			totalW = 2;
    			wIndex = 2;
    			totalH = 2;
    			hIndex = 1;
    		} else if (index == 3) {
    			totalW = 2;
    			wIndex = 1;
    			totalH = 2;
    			hIndex = 2;
    		} else if (index == 4) {
    			totalW = 2;
    			wIndex = 2;
    			totalH = 2;
    			hIndex = 2;
    		}
    		break;
    	case 5:
    		if (index == 1) {
    			totalW = 2;
    			wIndex = 1;
    			totalH = 2;
    			hIndex = 1;
    		} else if (index == 2) {
    			totalW = 2;
    			wIndex = 2;
    			totalH = 2;
    			hIndex = 1;
    		} else if (index == 3) {
    			totalW = 3;
    			wIndex = 1;
    			totalH = 2;
    			hIndex = 2;
    		} else if (index == 4) {
    			totalW = 3;
    			wIndex = 2;
    			totalH = 2;
    			hIndex = 2;
    		} else if (index == 5) {
    			totalW = 3;
    			wIndex = 3;
    			totalH = 2;
    			hIndex = 2;
    		}
    		break;
    	case 6:
    		if (index == 1) {
    			totalW = 3;
    			wIndex = 1;
    			totalH = 2;
    			hIndex = 1;
    		} else if (index == 2) {
    			totalW = 3;
    			wIndex = 2;
    			totalH = 2;
    			hIndex = 1;
    		} else if (index == 3) {
    			totalW = 3;
    			wIndex = 3;
    			totalH = 2;
    			hIndex = 1;
    		} else if (index == 4) {
    			totalW = 3;
    			wIndex = 1;
    			totalH = 2;
    			hIndex = 2;
    		} else if (index == 5) {
    			totalW = 3;
    			wIndex = 2;
    			totalH = 2;
    			hIndex = 2;
    		} else if (index == 6) {
    			totalW = 3;
    			wIndex = 3;
    			totalH = 2;
    			hIndex = 2;
    		}
    		break;
    	}
    	
    	int wa[] = getItemImgLen(destWeight, totalW, margin);
    	int ha[] = getItemImgLen(destHeight, totalH, margin);
    	result[0] = (wIndex != totalW)?wa[0]:wa[1];
    	result[1] = (hIndex != totalH)?ha[0]:ha[1];
    	
    	result[2] = getItemLocation(destWeight, totalW, wIndex, margin, wa[0]);
    	result[3] = getItemLocation(destHeight, totalH, hIndex, margin, ha[0]);
    	
    	System.out.println("getItemImgByDestImg2: [" + result[0] + ", " + result[1] + ", " + result[2] + ", " + result[3] + "]");
    	return result;
    }
    
    public static int[] getItemImgByDestImg3(int destWeight, int destHeight, int imgTotal, int index) {
    	int[] result = new int[4];
    	int margin = 2;//边距2
    	
    	int[][][] location = new int[][][] {{{1,1,2,1},{1,1,2,2}},
			{{1,1,2,1},{2,1,2,2},{2,2,2,2}},
			{{2,1,2,1},{2,2,2,1},{2,1,2,2},{2,2,2,2}},
			{{2,1,2,1},{2,2,2,1},{3,1,2,2},{3,2,2,2},{3,3,2,2}},
			{{3,1,2,1},{3,2,2,1},{3,3,2,1},{3,1,2,2},{3,2,2,2},{3,3,2,2}}};
		
		int totalW = location[imgTotal-2][index-1][0];
    	int wIndex = location[imgTotal-2][index-1][1];
    	int totalH = location[imgTotal-2][index-1][2];
    	int hIndex = location[imgTotal-2][index-1][3];
    	
		int wa[] = getItemImgLen(destWeight, totalW, margin);
    	int ha[] = getItemImgLen(destHeight, totalH, margin);
    	result[0] = (wIndex != totalW)?wa[0]:wa[1];
    	result[1] = (hIndex != totalH)?ha[0]:ha[1];
    	
    	result[2] = getItemLocation(destWeight, totalW, wIndex, margin, wa[0]);
    	result[3] = getItemLocation(destHeight, totalH, hIndex, margin, ha[0]);
    	
    	System.out.println("getItemImgByDestImg2: [" + result[0] + ", " + result[1] + ", " + result[2] + ", " + result[3] + "]");
    	return result;
    }
    
    public static void testAray(int imgTotal, int index) {
    	int[][][] location = new int[][][] {{{1,1,2,1},{1,1,2,2}},
			{{1,1,2,1},{2,1,2,2},{2,2,2,2}},
			{{2,1,2,1},{2,2,2,1},{2,1,2,2},{2,2,2,2}},
			{{2,1,2,1},{2,2,2,1},{3,1,2,2},{3,2,2,2},{3,3,2,2}},
			{{3,1,2,1},{3,2,2,1},{3,3,2,1},{3,1,2,2},{3,2,2,2},{3,3,2,2}}};
			
		int[] res = location[imgTotal-2][index-1];
		System.out.println("res:[" + res[0] + ", " + res[1] + ", " + res[2] + ", " + res[3] + "]");
    }
    
    /**
     * 拼接3张图片
     * @param imgPath1
     * @param imgPath2
     * @param imgPath3
     * @param destPath
     * @throws Exception 
     */
    public static void join3Img(String imgPath1, String imgPath2, String imgPath3, String destPath) throws Exception {
    	int destWeight = 800;
    	int destHeight = 800;
    	
    	//处理图片1——>临时图片1
    	String img1 = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y4.jpg";
    	String img1_temp = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y4.jpg";
    	subImg(img1, img1_temp, 400, 400);
    	
    	//处理图片2——>临时图片2
    	String img2 = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y2.jpg";
    	String img2_temp = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y2_temp.jpg";
    	subImg(img2, img2_temp, 400, 400);

    	//处理图片3——>临时图片3
    	String img3 = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y3.jpg";
    	String img3_temp = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y3_temp.jpg";
    	subImg(img3, img3_temp, 800, 400);
    	
    	//拼接临时图片1，临时图片2，临时图片3——>最终图片
    	String img1_2_3 = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y1_y2.jpg";
    	joinImagesVertical(img1_temp, img2_temp, img3_temp, "jpg", img1_2_3);
    }
    
    /**
     * 简单拼接图片
     * @param imgPath
     * @param destPath
     * @param destWeight
     * @param destHeight
     * @throws Exception
     */
    public static void joinImg(String[] imgPath, String destPath, int destWeight, int destHeight) throws Exception {
    	BufferedImage  imageNew  =  new  BufferedImage(destWeight, destHeight,BufferedImage.TYPE_INT_RGB); 
    	int[] itemImgInfo = null;
    	File  file  =  null;
    	BufferedImage  image = null;
    	int  width  =  0;
    	int  height  =  0;
    	int[]  imageArray  =  null;
    	for (int i = 0; i < imgPath.length; i++) {
    		System.out.println("拼接第" + i + "张图片");
    		//获取每个小图片应该要的目标大小及位置
    		itemImgInfo = getItemImgByDestImg(destWeight, destHeight, imgPath.length, i+1);
    		//按照目标处理原图
    		subImg(imgPath[i], imgPath[i], itemImgInfo[0], itemImgInfo[1]);
    		
    		file  =  new  File(imgPath[i]);      
            image = ImageIO.read(file);      
            width  =  image.getWidth();//图片宽度      
            height  =  image.getHeight();//图片高度      
            //从图片中读取RGB      
            imageArray  =  new  int[width*height];      
            imageArray  =  image.getRGB(0,0,width,height,imageArray,0,width);
            imageNew.setRGB(itemImgInfo[2],itemImgInfo[3],width,height,imageArray,0,width);//设置上半部分的左半边RGB
		}
    	File  outFile  =  new  File(destPath);      
        ImageIO.write(imageNew,  "jpg",  outFile);//写图片  
    	
    }
    
    /**
     * 拼接图片加上背景
     * @param imgPath
     * @param destPath
     * @param destWeight
     * @param destHeight
     * @throws Exception
     */
    public static void joinImgWithBackGround(String[] imgPath, String destPath, int destWeight, int destHeight) throws Exception {
    	//画一个背景图片
    	drawBackGround(destPath, destWeight, destHeight, "jpg");
    	int[] itemImgInfo = null;
    	
    	InputStream is= new FileInputStream(destPath);
    	BufferedImage image=ImageIO.read(is);
    	BufferedImage image2=null;
    	Graphics g=image.getGraphics();  
        InputStream is2= null;  
//        OutputStream os = null;
//        JPEGImageEncoder enc=null;
    	
    	//在背景图片上拼接其他图片
        try {
        	for (int i = 0; i < imgPath.length; i++) {
        		System.out.println("拼接第" + (i+1) + "张图片");
        		//获取每个小图片应该要的目标大小及位置
        		itemImgInfo = getItemImgByDestImg3(destWeight, destHeight, imgPath.length, i+1);
        		//按照目标处理原图
        		subImg(imgPath[i], imgPath[i], itemImgInfo[0], itemImgInfo[1]);
        		
//        		mergeBothImage(destPath, imgPath[i], itemImgInfo[2], itemImgInfo[3], destPath);
        		is2=new FileInputStream(imgPath[i]);  
                  
                image2=ImageIO.read(is2);  
                g.drawImage(image2,itemImgInfo[2], itemImgInfo[3],null);  
                
//                os = new FileOutputStream(destPath);  
//                enc=JPEGCodec.createJPEGEncoder(os);  
//                enc.encode(image);
                is2.close();
//                os.close();
        	}
        	
        	File outputfile = new File(destPath);  
            ImageIO.write(image, "jpg", outputfile);
        } finally {
//        	if(os != null){  
//                os.close();  
//            }  
        	if(is2 != null){  
                is2.close();  
            }  
            if(is != null){  
                is.close();  
            }  
        }
    	
    	
    }
    
    /**
     * 画背景
     * @param destPath
     * @param destWeight
     * @param destHeight
     * @throws IOException 
     */
    public static void drawBackGround(String destPath, int destWeight, int destHeight, String imgType) throws IOException {
    	final File file = new File(destPath);

    	if (file.exists()) {
			file.delete();
			file.createNewFile();
		}
		
		BufferedImage bi = new BufferedImage(destWeight, destHeight, BufferedImage.TYPE_INT_BGR);
		Graphics g = bi.getGraphics();
        g.setColor(new Color(255, 255, 255));
        g.fillRect(0, 0, destWeight, destHeight);
        g.dispose();
        ImageIO.write(bi, imgType, file);
    }
    
	public static void joinImg2() throws IOException {
		String imgPath1 = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y1.jpg";
		String imgPath2 = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y1.jpg";
		String background = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y1_ss.jpg";

		BufferedImage image = ImageIO.read(new File(imgPath1));
		int weight = image.getWidth();
		int height = image.getHeight();
		BufferedImage bi = new BufferedImage(weight, (height * 2) + 2, BufferedImage.TYPE_INT_BGR);
		final File file = new File(background);

		try {
			if (file.exists()) {
				file.delete();
				file.createNewFile();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		writeImage(bi, "jpg", file, weight, (height * 2) + 2);
		
//		groupImg(background, imgPath1);
		mergeBothImage(background, imgPath1, 0, 0, background);
		mergeBothImage(background, imgPath1, 0, height+2, background);
	}
	
	/** 通过指定参数写一个图片  */
    public static boolean writeImage(BufferedImage bi, String picType, File file, int weight, int height) {
        
    	Graphics g = bi.getGraphics();
        
        g.setColor(new Color(255, 255, 255));
        g.fillRect(0, 0, weight, height);
//        g.drawLine(0, 100, 100, 100);
        g.dispose();
        bi.flush();
        boolean val = false;
        try {
            val = ImageIO.write(bi, picType, file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return val;
    }
    
	public static void groupImg(String backgroundPath, String imgPath) throws IOException {
//		// 主图片的路径
//		InputStream is = new FileInputStream(backgroundPath);
//		// 通过JPEG图象流创建JPEG数据流解码器
//		JPEGImageDecoder jpegDecoder = JPEGCodec.createJPEGDecoder(is);
//		// 解码当前JPEG数据流，返回BufferedImage对象
//		BufferedImage buffImg = jpegDecoder.decodeAsBufferedImage();
		BufferedImage backgroundimage = ImageIO.read(new File(backgroundPath));
		// 得到画笔对象
		Graphics g = backgroundimage.getGraphics();

		// 小图片的路径
		if (imgPath != null) {
			ImageIcon imgIcon = new ImageIcon(imgPath);
			// 得到Image对象。
			Image img = imgIcon.getImage();
			// 将小图片绘到大图片上,5,300 .表示你的小图片在大图片上的位置。
			g.drawImage(img, 0, 0, null);

			// 设置颜色。
//			g.setColor(Color.WHITE);
		}
	}
	
    /** 
     * 合并图片(按指定初始x、y坐标将附加图片贴到底图之上) 
     * @param negativeImagePath 背景图片路径 
     * @param additionImagePath 附加图片路径 
     * @param x 附加图片的起始点x坐标 
     * @param y  附加图片的起始点y坐标 
     * @param toPath 图片写入路径 
     * @throws IOException 
     */  
    public static void mergeBothImage(String negativeImagePath,String additionImagePath,int x,int y,String toPath ) throws IOException{  
        InputStream is= null;  
        InputStream is2= null;  
        OutputStream os = null;  
        try{  
            is=new FileInputStream(negativeImagePath);  
            is2=new FileInputStream(additionImagePath);  
            BufferedImage image=ImageIO.read(is);  
            BufferedImage image2=ImageIO.read(is2);  
            Graphics g=image.getGraphics();  
            g.drawImage(image2,x,y,null);  
            os = new FileOutputStream(toPath);  
            JPEGImageEncoder enc=JPEGCodec.createJPEGEncoder(os);  
            enc.encode(image);  
        }catch(Exception e){  
            e.printStackTrace();  
        }finally{  
            if(os != null){  
                os.close();  
            }  
            if(is2 != null){  
                is2.close();  
            }  
            if(is != null){  
                is.close();  
            }  
        }  
    }
    
    
    /**
     * 定长拼接：每个图片最终大小一开始就可以确定，然后，该放大放大， 该缩小缩小，但都是等比例缩放，然后截取
     * 测试拼接图片
     * 两种大情况，每种大情况分为5中拼接方式
     * 两种大情况：定长度（同时也知道比例）、不定长度（定比例）
     * 5中拼接方式：2，3,4,5,6  张图片拼接
     * @throws Exception 
     */
    public static void testJoinImg1() throws Exception {
//    	System.out.println("----------测试subLenght----------");
//    	System.out.println("原图比目标图长宽都长》》");
//    	double priWeight1 = 1000;
//    	double priHeight1 = 700;
//    	double needWeight1 = 500;
//    	double needHeight1 = 600;
//    	System.out.println("期望： resultRatio=0.8571, tagSub=1, tagLen=500");
//    	subLenght(priWeight1, priHeight1, needWeight1, needHeight1);
//    	
//    	System.out.println("原图的宽或高比目标图长》》");
//    	double priWeight2 = 1000;
//    	double priHeight2 = 700;
//    	double needWeight2 = 800;
//    	double needHeight2 = 900;
//    	System.out.println("期望： resultRatio=1.2857, tagSub=1, tagLen=800");
//    	subLenght(priWeight2, priHeight2, needWeight2, needHeight2);
//    	
//    	
//    	System.out.println("原图的宽高都比目标图短》》");
//    	double priWeight3 = 1000;
//    	double priHeight3 = 700;
//    	double needWeight3 = 1200;
//    	double needHeight3 = 1000;
//    	System.out.println("期望： resultRatio=1.42857, tagSub=1, tagLen=1200");
//    	subLenght(priWeight3, priHeight3, needWeight3, needHeight3);
//    	
//    	System.out.println("----------测试subImg----------");
//    	try {
//			subImg();//
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
    	
    	//测试纵向拼接图片
//    	String firstSrcImagePath = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y1.jpg";
//    	String secondSrcImagePath = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y1.jpg";
//    	String imageFormat = "jpg";
//    	String toPath = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y1_y1.jpg";
//    	joinImagesVertical(firstSrcImagePath, secondSrcImagePath, imageFormat, toPath);
    	
    	//测试截取并拼接图片
    	String imgPath1 = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y1.jpg";
//    	String imgPath1_big = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y1_big.jpg";
    	String imgPath2 = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y2.jpg";
    	String imgPath3 = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y3.jpg";
    	String destPath = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y1_y2_y3_22.jpg";
//    	try {
//			join2Img(imgPath1, imgPath2, destPath);
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
    	
//    	try {
//			join3Img(imgPath1, imgPath2, imgPath3, destPath);
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
    	
//    	try {
//			zoomImage1(imgPath1, imgPath1_big, 1.23);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
    	
//    	String[] imgPath = new String[2];
//    	destPath = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\dest2.jpg";
//    	imgPath[0] = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y1.jpg";
//    	imgPath[1] = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y2.jpg";
//    	
//    	String[] imgPath = new String[3];
//    	destPath = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\dest3.jpg";
//    	imgPath[0] = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y1.jpg";
//    	imgPath[1] = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y3.jpg";
//    	imgPath[2] = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y4.jpg";
//    	
//    	String[] imgPath = new String[4];
//    	destPath = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\dest4.jpg";
//    	imgPath[0] = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y1.jpg";
//    	imgPath[1] = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y2.jpg";
//    	imgPath[2] = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y3.jpg";
//    	imgPath[3] = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y4.jpg";
//    	
//    	String[] imgPath = new String[5];
//    	destPath = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\dest5.jpg";
//    	imgPath[0] = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y1.jpg";
//    	imgPath[1] = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y2.jpg";
//    	imgPath[2] = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y3.jpg";
//    	imgPath[3] = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y4.jpg";
//    	imgPath[4] = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y5.jpg";
//
    	String[] imgPath = new String[6];
    	destPath = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\dest6.jpg";
    	imgPath[0] = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y1.jpg";
    	imgPath[1] = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y2.jpg";
    	imgPath[2] = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y3.jpg";
    	imgPath[3] = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y4.jpg";
    	imgPath[4] = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y5.jpg";
    	imgPath[5] = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试\\y6.jpg";
    	try {
//			joinImg(imgPath, destPath, 800, 800);
			joinImgWithBackGround(imgPath, destPath, 800, 800);
		} catch (IOException e) {
			e.printStackTrace();
		}
    	
    	
    }
    
    /**
     * 定比例拼接
     */
    public void testJoinImg2() {
    	
    	
    }
    
    

    
    
    
    /**
     * 测试截取图片
     */
    public static void testSubImg() {
    	// TODO Auto-generated method stub
    			String imgPath1 = "F:/worksource/JKCT/HB/temp/testImg/11.jpg";
    			String imgPath2 = "F:/worksource/JKCT/HB/temp/testImg/22.jpg";
    			String imgPath3 = "F:/worksource/JKCT/HB/temp/testImg/test.PNG";
    			String imgPath4 = "F:/worksource/JKCT/HB/temp/testImg/TIM图片20181121143652.png";
    			String imgPath5 = "F:/worksource/JKCT/HB/temp/testImg/头像.jpg";//500x500
    			String imgPath6 = "F:/worksource/JKCT/HB/temp/testImg/r (1).jpg";//326x207
    			
    			String imgPath_dest111 = "F:/worksource/JKCT/HB/temp/testImg/dest111.PNG";
    			
    			String imgPath_dest1 = "F:/worksource/JKCT/HB/temp/testImg/dest11.PNG";
    			String imgPath_dest2 = "F:/worksource/JKCT/HB/temp/testImg/dest22.jpg";
    			String imgPath_dest3 = "F:/worksource/JKCT/HB/temp/testImg/dest33.jpg";
    			String imgPath_dest4 = "F:/worksource/JKCT/HB/temp/testImg/dest44.jpg";
    			String imgPath_dest5 = "F:/worksource/JKCT/HB/temp/testImg/dest55.jpg";
    			String imgPath_dest6 = "F:/worksource/JKCT/HB/temp/testImg/dest66.jpg";
    			String imgPath_dest7 = "F:/worksource/JKCT/HB/temp/testImg/dest77.jpg";
    			String imgPath_dest8 = "F:/worksource/JKCT/HB/temp/testImg/dest88.jpg";
    			String imgPath_dest9 = "F:/worksource/JKCT/HB/temp/testImg/dest99.jpg";
    			String imgPath_dest10 = "F:/worksource/JKCT/HB/temp/testImg/dest100.jpg";
    			
    			
    			try {
//    				zoomImage(imgPath3, imgPath_dest1, 500, 683);
//    				zoomImage(imgPath1, imgPath_dest2, 500, 1000);
//    				
//    				
//    				readUsingImageReader(imgPath3, imgPath_dest111, 0, 0, 400, 400, "PNG");
//    				
    				aotoSubImg(imgPath6, imgPath_dest2, 160, 160);
//    				aotoSubImg(imgPath5, imgPath_dest2, 160, 160);
//    				aotoSubImg(imgPath1, imgPath_dest3, 1324, 300);
//    				
//    				aotoSubImg(imgPath1, imgPath_dest4, 600, 683);
//    				aotoSubImg(imgPath1, imgPath_dest5, 1024, 683);
//    				aotoSubImg(imgPath1, imgPath_dest6, 1324, 683);
//    				
//    				aotoSubImg(imgPath1, imgPath_dest7, 600, 800);
//    				aotoSubImg(imgPath1, imgPath_dest8, 1024, 800);
//    				aotoSubImg(imgPath1, imgPath_dest9, 1324, 800);
//    				
//    				aotoSubImg(imgPath1, imgPath_dest10, 200, 133);
    				
    			} catch (Exception e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			
    			
//    			Number[] rs = getLengthAndWidth3(5, 5, 4, 6);
//    			System.out.println("length=" + rs[0] + ", width=" + rs[1] + ", ifshort=" + rs[2] + ", ratio=" + rs[3]);
//    			Number[] rs1 = getLengthAndWidth3(5, 5, 6, 8);
//    			System.out.println("length=" + rs1[0] + ", width=" + rs1[1] + ", ifshort=" + rs1[2] + ", ratio=" + rs1[3]);
//    			Number[] rs2 = getLengthAndWidth3(5, 5, 5, 5);
//    			System.out.println("length=" + rs2[0] + ", width=" + rs2[1] + ", ifshort=" + rs2[2] + ", ratio=" + rs2[3]);
//    			Number[] rs3 = getLengthAndWidth3(5, 5, 6, 4);
//    			System.out.println("length=" + rs3[0] + ", width=" + rs3[1] + ", ifshort=" + rs3[2] + ", ratio=" + rs3[3]);
//    			Number[] rs4 = getLengthAndWidth3(5, 5, 3, 4);
//    			System.out.println("length=" + rs4[0] + ", width=" + rs4[1] + ", ifshort=" + rs4[2] + ", ratio=" + rs4[3]);
    	//
//    			Number[] rs5 = getLengthAndWidth3(1024, 683, 200, 133);
//    			System.out.println("length=" + rs5[0] + ", width=" + rs5[1] + ", ifshort=" + rs5[2] + ", ratio=" + rs5[3]);
//    			Number[] rs6 = getLengthAndWidth3(1024, 683, 1024, 300);
//    			System.out.println("length=" + rs6[0] + ", width=" + rs6[1] + ", ifshort=" + rs6[2] + ", ratio=" + rs6[3]);
    }
    

	public static void main(String[] args) {
		try {
			testJoinImg1();
//			joinImg2();
//			testAray(2, 1);
//			testAray(2, 2);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}

}
